package com.suke.czx.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.UUID;

/**
 * 文件上传工具类（简单粗暴，够用就行）
 */
@Slf4j
@Component
public class FilezUtils {
    @Value("${file.upload-dir}")
    private String uploadDir; // 临时变量

    @Value(value = "${file.download-dir}")
    private String downloadDir;

    @Autowired
    private Environment env;

    public static String UPLOAD_DIR;
    public static String DOWNLOAD_DIR;
    @PostConstruct
    public void init() {
        String port = env.getProperty("server.port", "8080");
        String contextPath = env.getProperty("server.servlet.context-path", "");
        String address = "http://127.0.0.1:" + port + contextPath;
        log.info("服务根路径: {}", address);

        UPLOAD_DIR = uploadDir; // 初始化 static
        DOWNLOAD_DIR = address + downloadDir;
        log.info("静态上传目录: {}", UPLOAD_DIR);
        log.info("静态下载目录: {}", DOWNLOAD_DIR);

    }
    // 默认上传路径（项目根目录下的 uploads 文件夹）

    /**
     * 上传文件到本地，返回访问URL
     *
     * @param file 上传的文件
     * @return 文件访问路径（如：/uploads/xxx.jpg）
     * @throws IOException 如果上传失败
     */
    public static String upload(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }

        // 1. 确保上传目录存在
        File uploadDir = new File(UPLOAD_DIR);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 2. 生成唯一文件名（避免重名覆盖）
        String originalFilename = file.getOriginalFilename();
        String fileExtension = StringUtils.getFilenameExtension(originalFilename);
        String uniqueFileName = UUID.randomUUID() + "." + fileExtension;

        // 3. 存储文件
        Path filePath = Paths.get(UPLOAD_DIR, uniqueFileName);
        Files.write(filePath, file.getBytes());

        // 4. 返回相对路径（如：/uploads/xxx.jpg）
        // UPLOAD_DIR + "/" +
        return DOWNLOAD_DIR + "/" + uniqueFileName;
//        return uniqueFileName;
    }


    /**
     * 读取文件为字节数组（适合图片、二进制文件）
     *
     * @param filePath 文件路径（如：/uploads/xxx.jpg）
     * @return 文件字节数组
     * @throws IOException 如果文件不存在或读取失败
     */
    public static byte[] readFileToBytes(String filePath) throws IOException {
        Path path = Paths.get(UPLOAD_DIR, filePath.replace("/" + UPLOAD_DIR + "/", ""));
        return Files.readAllBytes(path);
    }
    /**
     * 读取文件为字符串（适合文本文件，如JSON、TXT）
     *
     * @param filePath 文件路径（如：/uploads/xxx.txt）
     * @return 文件内容字符串
     * @throws IOException 如果文件不存在或读取失败
     */
    public static String readFileToString(String filePath) throws IOException {
        byte[] bytes = readFileToBytes(filePath);
        return new String(bytes, StandardCharsets.UTF_8);
    }
    /**
     * 检查文件是否存在
     *
     * @param filePath 文件路径（如：/uploads/xxx.jpg）
     * @return true=存在，false=不存在
     */
    public static boolean exists(String filePath) {
        Path path = Paths.get(UPLOAD_DIR, filePath.replace("/" + UPLOAD_DIR + "/", ""));
        return Files.exists(path);
    }

    private static final String[] WHITELIST_EXTENSIONS = {
            "jpg", "jpeg", "png", "gif", "pdf", "doc", "docx", "xls", "xlsx"
    };


    public static boolean isSafeExtension(String filename) {
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
        return Arrays.asList(WHITELIST_EXTENSIONS).contains(ext);
    }


}

